import React, { useEffect, useRef } from 'react';
import * as echarts from 'echarts';

const StackedChart = ({ data, legend }) => {
  const chartRef = useRef(null);

  useEffect(() => {
    const chartInstance = echarts.init(chartRef.current);

    const option = {
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'shadow',
        },
      },
      legend: {
        data: legend,
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '3%',
        containLabel: true,
      },
      xAxis: [
        {
          type: 'category',
          data: data.map(item => item.key), // 假设每行数据的key是唯一的，用作x轴的标签
        },
      ],
      yAxis: [
        {
          type: 'value',
        },
      ],
      series: legend.map(leg => ({
        name: leg,
        type: 'bar',
        stack: 'total',
        emphasis: {
          focus: 'series',
        },
        data: data.map(item => item[leg]), // 假设每个legend项在data中有对应的值
      })),
    };

    chartInstance.setOption(option);

    return () => {
      chartInstance.dispose();
    };
  }, [data, legend]);

  return <div ref={chartRef} style={{ width: '100%', height: '400px' }}></div>;
};

export default StackedChart;